package ar.com.ford.it.fullEconomics.logic;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.CurrencyDao;
import ar.com.ford.it.fullEconomics.persistence.dao.EconomicValueDao;
import ar.com.ford.it.fullEconomics.persistence.dao.PartDao;
import ar.com.ford.it.fullEconomics.persistence.dao.SupplierDao;
import ar.com.ford.it.fullEconomics.persistence.dao.SupplyDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesm01Currency;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp04Supply;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp05Pricing;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.SupplyStruct;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class SupplyLogic {

    private static final String CLASS_NAME = SupplyLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    public Collection<SupplyStruct> findSupply(Teesp04Supply supply)
            throws FullEconomicsException {

        String METHOD_NAME = "findSupply";
        log.entering(CLASS_NAME, METHOD_NAME);
        SupplyDao dao = new SupplyDao();
        Collection<Teesp04Supply> ret = null;
        Collection<SupplyStruct> resultTotal = new ArrayList<SupplyStruct>();
        Teesp05Pricing pricingFind = new Teesp05Pricing();
        try {
            ret = dao.findSupply(supply);
            for (Teesp04Supply supplyS : ret) {
                SupplyStruct supplyC = new SupplyStruct();
                Teesp05Pricing pricing = new Teesp05Pricing();
                supplyC.setTeesp04Supply(supplyS);
                pricingFind.setTeesp04Supply(supplyS);
                pricing = dao.findPricing(pricingFind);
                if (pricing == null) {
                    supplyC.setTeesp05Pricing(new Teesp05Pricing());
                } else {
                    supplyC.setTeesp05Pricing(pricing);
                }

                resultTotal.add(supplyC);
            }
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Supply Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Supply.FINDALL);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return resultTotal;

    }

    public void createSupply(Teesp04Supply supply, FullEconomicsWslxUser user)
            throws FullEconomicsException {
        String METHOD_NAME = "createSupply";
        log.entering(CLASS_NAME, METHOD_NAME);

        SupplyDao dao = new SupplyDao();
        Teesp04Supply newSupply = new Teesp04Supply();
        try {
            PersistenceUtil.newTransaction();
            newSupply.setEesp04PlantCodeC(user.getTeesg01Plant());
            newSupply.setTeesp01Part((Teesp01Part) (new PartDao())
                    .getObjForUpdate(supply.getTeesp01Part()));
            newSupply.setTeess01Supplier((Teess01Supplier) (new SupplierDao())
                    .getObjForUpdate(supply.getTeess01Supplier()));
            if (supply.getEesp04SupplyTvmCurrencyC() != null)
                newSupply
                        .setEesp04SupplyTvmCurrencyC((Teesm01Currency) (new CurrencyDao())
                                .getObjForUpdate(supply
                                        .getEesp04SupplyTvmCurrencyC()));
            newSupply.setEesp04CreateUserC(user.getId());
            newSupply
                    .setEesp04CreateS(new Timestamp(System.currentTimeMillis()));
            newSupply.setEesp04LastUpdtUserC(user.getId());
            newSupply.setEesp04LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            newSupply.setEesp04LastUpdtTvmUserC(user.getId());
            newSupply.setEesp04LastUpdtTvmS(new Timestamp(System
                    .currentTimeMillis()));
            newSupply.setEesp04SupplySharePercentP(supply
                    .getEesp04SupplySharePercentP());
            newSupply.setEesp04SupplyTvmAmountA(supply
                    .getEesp04SupplyTvmAmountA());
            newSupply.setTeesx03Intflog(supply.getTeesx03Intflog());
            dao.createSupply(newSupply);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Part Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Supply.CREATE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Actualizacion de Supply
     * 
     * @param supply
     * @throws FullEconomicsException
     */
    public void updateSupply(Teesp04Supply supply, FullEconomicsWslxUser user)
            throws FullEconomicsException {
        String METHOD_NAME = "updateSupply";
        log.entering(CLASS_NAME, METHOD_NAME);
        Teesp04Supply workingCopy = new Teesp04Supply();
        try {

            PersistenceUtil.newTransaction();
            PersistenceUtil.getPersistenceManager().clearCache();
            workingCopy = (new SupplyDao()).getUpdateSupply(supply);
            workingCopy.setEesp04SupplySharePercentP(supply
                    .getEesp04SupplySharePercentP());
            workingCopy.setEesp04SupplyTvmAmountA(supply
                    .getEesp04SupplyTvmAmountA());
            
            if (null!=supply.getEesp04SupplyTvmCurrencyC())
            	workingCopy.setEesp04SupplyTvmCurrencyC((new CurrencyDao())
            			.getCurrencyForUpdate(supply.getEesp04SupplyTvmCurrencyC().getEesm01CurrencyCodeC()));
            
            workingCopy.setEesp04LastUpdtUserC(user.getId());
            workingCopy.setEesp04LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            
            if ((null!=supply.getEesp04SupplyTvmCurrencyC()) && ((workingCopy.getEesp04SupplyTvmCurrencyC()
                    .getEesm01CurrencyCodeC() != supply
                    .getEesp04SupplyTvmCurrencyC().getEesm01CurrencyCodeC())
                    || (workingCopy.getEesp04SupplyTvmAmountA() != supply
                            .getEesp04SupplyTvmAmountA()))) {
                workingCopy.setEesp04LastUpdtTvmUserC(user.getId());
                workingCopy.setEesp04LastUpdtTvmS(new Timestamp(System
                        .currentTimeMillis()));
            }
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {

            pe.printStackTrace();
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Economic Index Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.EconomicValue.UPDATE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    public boolean deletedSupply(Teesp04Supply supply)
            throws FullEconomicsException {
        String METHOD_NAME = "deleteEconomicValue";
        log.entering(CLASS_NAME, METHOD_NAME);
        boolean res = true;
        try {
            PersistenceUtil.newTransaction();
            SupplyDao dao = new SupplyDao();
            dao.deleteSupply(supply);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException e) {
            res = false;
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Deleted Supply Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Supply.DELETE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    public Collection<Teesp04Supply> findAllSupply(Teesp04Supply supply)
            throws FullEconomicsException {

        String METHOD_NAME = "findAllSupply";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesp04Supply> res = null;
        EconomicValueDao dao = new EconomicValueDao();
        String[] fields = { "teesp01Part", "eesp04PlantCodeC" };
        Object[] values = { supply.getTeesp01Part(),
                supply.getEesp04PlantCodeC() };

        try {
            res = dao.findAll(new Teesp04Supply(), fields, values);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find all Supply Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Supply.FINDALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    public Teesp04Supply getSupplyByPk(Teesp04Supply supply)
            throws FullEconomicsException {

        String METHOD_NAME = "getSupplyByPk";
        log.entering(CLASS_NAME, METHOD_NAME);
        Teesp04Supply res = null;
        SupplyDao dao = new SupplyDao();

        try {
            res = dao.getSupplyByPk(supply);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find by pk Supply Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Supply.FINDALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return res;
    }

    /**
     * Busca los Supplies segun el Supplier y la planta seteados en "supply"
     * 
     * @param supply
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesp04Supply> findSuppliesBySupplier(Teesp04Supply supply)
            throws FullEconomicsException {
        String METHOD_NAME = "findSuppliesBySupplier";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesp04Supply> ret = null;
        SupplyDao dao = new SupplyDao();
        String[] fields = { "eesp04PlantCodeC", "teess01Supplier" };
        Object[] values = { supply.getEesp04PlantCodeC(),
                supply.getTeess01Supplier() };

        try {
            ret = dao.findAll(new Teesp04Supply(), fields, values);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find all Supply Exception", e);

            // FIXME Cambiar el tipo de excepcion!!
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.Supply.FINDALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return ret;
    }

}
